//
//  ProtocolViewController.m
//
//  Created by 周成龙
//

#import "ProtocolViewController.h"

//-------------------- POCNetworkFetcher
@class POCNetworkFetcher;
@protocol POCNetworkFetcherDelegate <NSObject>
@optional;
- (void)networkFetcher:(POCNetworkFetcher *)fetcher didReceiveData:(NSData *)data;
- (void)networkFetcher:(POCNetworkFetcher *)fetcher didFailureWithError:(NSError *)error;
- (void)networkFetcher:(POCNetworkFetcher *)fetcher didUpdateProgressTo:(CGFloat)progress;
@end

@interface POCNetworkFetcher : NSObject
@property (nonatomic, weak) id<POCNetworkFetcherDelegate>delegate;

- (void)fetcherData;
@end
@implementation POCNetworkFetcher {
    struct {
        unsigned int didReceiveData         :1;
        unsigned int didFailureWithError    :1;
        unsigned int didUpdateProgressTo    :1;
    } _delegateFlag;
}

- (void)fetcherData {
//    if ([_delegate respondsToSelector:@selector(networkFetcher:didReceiveData:)]) {
//        [_delegate networkFetcher:self didReceiveData:nil];
//    }
    
    // 上面的代码可以替换为
    if (_delegateFlag.didReceiveData) {
        [_delegate networkFetcher:self didReceiveData:nil];
    }
}

// 缓存代理
- (void)setDelegate:(id<POCNetworkFetcherDelegate>)delegate {
    _delegate = delegate;
    
    _delegateFlag.didReceiveData = [_delegate respondsToSelector:@selector(networkFetcher:didReceiveData:)];
    _delegateFlag.didFailureWithError = [_delegate respondsToSelector:@selector(networkFetcher:didFailureWithError:)];
    _delegateFlag.didUpdateProgressTo = [_delegate respondsToSelector:@selector(networkFetcher:didUpdateProgressTo:)];
}

@end


//-------------------- POCDataModel
@interface POCDataModel : NSObject <POCNetworkFetcherDelegate>

@end

@implementation POCDataModel
- (void)networkFetcher:(POCNetworkFetcher *)fetcher didReceiveData:(NSData *)data {
    NSLog(@"有数据了");
}

- (void)networkFetcher:(POCNetworkFetcher *)fetcher didFailureWithError:(NSError *)error {
    NSLog(@"有错误了");
}

- (void)networkFetcher:(POCNetworkFetcher *)fetcher didUpdateProgressTo:(CGFloat)progress {
    NSLog(@"更新啦");
}
@end


//-------------------- ProtocolViewController
@interface ProtocolViewController ()

@end

@implementation ProtocolViewController
#pragma mark - LifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    /**
     1. 委托模式为对象提供了一套接口，使其可由此将相关事件告知其他对象。
     2. 将委托对象应该支持接口定义成协议，在协议中把可能需要处理的时间定义成方法。
     3. 当某对象需要从另外一个对象中获取数据时，可以使用委托模式，这总清净下，该模式亦称“数据源协议”
     4. 若有必要，可实现含有段位的结构体，将委托对象是否能响应相关协议方法这一信息缓存值其中。
     */
    
}

#pragma mark - Private

#pragma mark - Delegate

#pragma mark - Setter / Getter


@end
